// packageA/pages/repairDetail/repairDetail.js
const app = getApp();
import CommonService from '../../../utils/service/commonService.js';
import Toast from '../../../miniprogram_npm/@vant/weapp/toast/toast';
const util = require('../../../utils/util');
//去掉末尾的0
const regexp=/(?:\.0*|(\.\d+?)0+)$/;

Page({

  /**
   * 页面的初始数据
   */
  data: {
    //传参
    paramObj:null,     
    //信息回显
    editInfo:{},
    //折叠面板
    activeLogistics: null,
    activePart: null,
    activeCost: null,
    //人员类型
    typeMap:null,
    //当前登录用户
		user:null
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.setData({ 
      user: app.globalData.userInfo
    })

    //获取服务人员类型(字典)
    this.getType();

    if(options.paramObj){
      let paramObj=JSON.parse(options.paramObj);
      console.log('维修详情传参');
      console.log(paramObj);

      this.setData({
        paramObj: paramObj
      })

      if(paramObj.repairId){
        //获取修改的数据
        this.getInfo();
      }
    }  
  },

  //获取修改的数据
  getInfo(){
    Toast.loading({
      duration: 1000,
      forbidClick: false,
      message: '加载中...'
    });

    let param = {
      isAuth: false,
      className: 'afterSaleMaintainOrder',
      data: {
        id:this.data.paramObj.repairId,
        selectFields: ["id", "orderNo", "equipmentNo", "depart", "project", "equipmentId", "receiver", "state", "costs","processingTime", "expirationTime", "serviceDetails", "businessType", "logistics", "repairInfo","completeDate", "closeOrderDate", "faultType", "processMode", "processResult", "trueFault", "pic","memberTypeName","remark","callRecord"]
      }
    }

    CommonService.goFindList(param).then(res => {
      if(res.data.data && res.data.data.result && res.data.data.result.length) {
        let result=res.data.data.result[0];

        console.log('维修详情');
        console.log(result);
        
        //业务类型
        if(result.businessType){       
          switch(result.businessType){
            case 1:
              result.self_businessType='销售';
              break;
            case 2:
              result.self_businessType='租赁-授信';
              break;
            case 3:
              result.self_businessType='租赁-非授信';
              break;
            case 4:
              result.self_businessType='试机';
              break;
            case 5:
              result.self_businessType='存量改造';
              break;
          }
        }
        
        if(result.repairInfo){
          //报修时间
          if(result.repairInfo.date){
            result.self_repairDate=util.timeFormat(result.repairInfo.date);
          }

          //出厂/入场日期
          if(result.repairInfo.createDate){
            result.self_createDate=util.timeFormat(result.repairInfo.createDate);
          }

          //故障图片
          if(result.repairInfo.pic){
            result.self_repairPic=JSON.parse(result.repairInfo.pic);
          }
          
          //报修信息-省市区+地址
          let str='';
          if(result.repairInfo.addressArea && result.repairInfo.addressArea.length){
            result.repairInfo.addressArea.forEach(item=>{
              str+=item.name+'-';
            });
          }
          result.repairInfo.self_address=str+result.repairInfo.address;
        }

        //只有一条物流则展开
        if(result.logistics && result.logistics.length==1){
          this.setData({
            activeLogistics: (result.logistics)[0].id
          })
        }

        //物流费用保留两位小数并去掉末尾的0
        if(result.logistics && result.logistics.length){
          result.logistics.forEach(item => {
            if(item.freight!=null && item.freight!=''){
              item.freight=(Number(item.freight)).toFixed(2).replace(regexp,'$1');
            }

            //配件费
            if(item.parts && item.parts.length){
              item.parts.forEach(item2 => {
                if(item2.salePrice!=null && item2.salePrice!=''){
                  item2.salePrice=(Number(item2.salePrice)).toFixed(2).replace(regexp,'$1');
                }
              });
            }

            //物流的省市区+地址
            let str1='';
            if(item.addressArea && item.addressArea.length){
              item.addressArea.forEach(item2=>{
                str1+=item2.name+'-';
              });
            }
            item.self_address=str1+item.shippingAddress;
          });
        }

        //只有一条费用则展开
        if(result.costs && result.costs.length==1){
          this.setData({
            activeCost: 0
          })  
        }

        //费用-人员类型
        if(result.costs && result.costs.length){
          result.costs.forEach(item => {
            if(this.data.typeMap){
              if(item.staff.type){
                item.staff.typeName=this.data.typeMap.get(item.staff.type);
              }
            }

            //费用保留两位小数并去掉末尾的0
            if(item.cost!=null && item.cost!=''){
              item.cost=(Number(item.cost)).toFixed(2).replace(regexp,'$1');
            }
          });
        }  
       
        this.setData({
          editInfo: result
        })
      }
    }).catch((error) => {
    })
  },

  //预览图片
  onPreviewImage(e) {
    let detail = e.target.dataset.detail;
    let src = e.target.dataset.src;

    wx.previewImage({
      current: src,
      urls: detail
    })
  },

  //预览图片
  onPreviewImage2(e) {
    let detail = e.target.dataset.detail;
    let src = e.target.dataset.src;

    let newArr=[];
    for(let i=0;i<detail.length;i++){
      newArr.push(detail[i].url);
    }

    wx.previewImage({
      current: src,
      urls: newArr
    })
  },

  //切换物流折叠面板
  onChangeLogistics(event) {
    this.setData({
      activeLogistics: event.detail
    })
  },

  //切换配件折叠面板
  onChangePart(event) {
    this.setData({
      activePart: event.detail
    })
  }, 
  
  onChangeCost(event) {
    this.setData({
      activeCost: event.detail,
    })
  },
  
  //获取服务人员类型(字典)
  getType(){
    let param = {
      isAuth: false,
      className: 'dictionary',
      data: {
        searchAll: true,
        key: 'serviceStaffType',
        selectFields: ['id','name']
      }
    }

    CommonService.goFindList(param).then(res=>{
      if(res.data.data && res.data.data.result && res.data.data.result.length){
        let result=res.data.data.result;
        let typeMap=new Map();
        let arr=[];
        result.forEach(item => {
          typeMap.set(item.id,item.name);
        });
        this.setData({
          typeMap: typeMap
        })
      }
    }).catch((error) => {
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  }
})